﻿angular.module("simpleDirective", []);

angular.module("simpleDirective").controller("simpleController", ["$scope",
    function($scope) {
        $scope.good = "good";
        $scope.message = {
            name: "hello",
            address: "gogo"
        };
        $scope.form = {};
        $scope.sayMessage = function() {
            Console.log($scope.message);
        };
    }
]);

angular.module("simpleDirective").directive("hello", function() {
        return {
            require: "?ngModel",
            restrict: "EA",
            scope: {
                message: "=hello"
            },
            link:function(scope, element, attrs, ctrl) {

                scope.sayHello = "hello";
            }
        }
    }
);

angular.module("simpleDirective").directive('log', function () {

    return {
        controller: function ($scope, $element, $attrs, $transclude) {
            console.log($attrs.log + ' (controller)');
        },
        compile: function compile(tElement, tAttributes) {
            console.log(tAttributes.log + ' (compile)');
            return {
                pre: function preLink(scope, element, attributes) {
                    console.log(attributes.log + ' (pre-link)');
                },
                post: function postLink(scope, element, attributes) {
                    console.log(attributes.log + ' (post-link)');
                }
            };
        }
    };

});

angular.module("simpleDirective").directive('contenteditable', function () {
    return {
        restrict: 'A', // only activate on element attribute
        require: '?ngModel', // get a hold of NgModelController
        scope: {},
        link: function (scope, element, attrs, ngModel) {
            if (!ngModel)
                return; // do nothing if no ng-model

            //setInterval(function () {
            //    if (angular.element('#contenteditable').scope().form)
            //        console.log(angular.element('#contenteditable').scope().form.userContent);

            //    if (angular.element('#textarea').scope().form)
            //        console.log(angular.element('#textarea').scope().form.userContent);
            //}, 1000);

            //// Specify how UI should be updated
            ngModel.$render = function () {
                element.html(ngModel.$viewValue || '');
            };

            // Listen for change events to enable binding
            element.bind('blur keyup change', function () {
                scope.$apply(read);
            });
            read(); // initialize

            // Write data to the model
            function read() {
                ngModel.$setViewValue(element.html());
            }
        }
    };
});

